package modbus

import (
	"github.com/project-flogo/core/data/coerce"
)

type Settings struct {
	ClientType string                 `md:"clientType" json:"clientType,omitempty"`
	Params     map[string]interface{} `md:"params" json:"params,omitempty"`
}

type Input struct {
	Op     string                 `md:"op" json:"op,omitempty"`
	Params map[string]interface{} `md:"params" json:"params,omitempty"`
}

func (r *Input) ToMap() map[string]interface{} {
	return map[string]interface{}{
		"op":     r.Op,
		"params": r.Params,
	}
}

func (r *Input) FromMap(values map[string]interface{}) error {
	op, err := coerce.ToString(values["op"])
	if err != nil {
		return err
	}
	r.Op = op

	params, err := coerce.ToObject(values["params"])
	if err != nil {
		return err
	}
	r.Params = params
	return nil
}

type Output struct {
	Results []byte `md:"results" json:"results,omitempty"`
	Err     string `md:"err" json:"err,omitempty"`
}

func (r *Output) ToMap() map[string]interface{} {
	return map[string]interface{}{
		"results": r.Results,
		"err":     r.Err,
	}
}

func (r *Output) FromMap(values map[string]interface{}) error {
	results, err := coerce.ToBytes(values["results"])
	if err != nil {
		return err
	}
	r.Results = results

	errStr, err := coerce.ToString(values["err"])
	if err != nil {
		return err
	}
	r.Err = errStr

	return nil
}
